<template>
  <div id="dep-tree">
    <a-input-search style="margin-bottom: 8px" @change="onChange" placeholder="Search" />
    <a-tree
      :treeData="treeData"
      @expand="onExpand"
      :showLine="true"
      :selectedKeys="selectKey"
      :expandedKeys="expandedKeys"
      :autoExpandParent="autoExpandParent"
      @select="selectNode"
      :defaultExpandAll="true"
    >
      <template v-if="item.title.indexOf(searchValue) > -1" slot="custom" slot-scope="item">
        <div :class="item.status == 1 ? 'depStop tree-title' : 'tree-title'">
          {{ item.title.substr(0, item.title.indexOf(searchValue)) }}
          <span style="color: #f50">{{ searchValue }}</span>
          {{ item.title.substr(item.title.indexOf(searchValue) + searchValue.length) }}
          {{ item.status == 1 ? '(停用)' : '' }}
        </div>
        <!--        <div v-else :title="item.title" :class="item.status == 1 ? 'depStop tree-title' : 'tree-title'">-->
        <!--          {{ item.title }}{{ item.status == 1 ? '(停用)' : '' }}-->
        <!--        </div>-->
        <div class="tree-todo">
          <a-dropdown>
            <a class="ant-dropdown-link" @click="e => e.preventDefault()">操作<a-icon type="down" /> </a>
            <a-menu slot="overlay">
              <a-menu-item key="0">
                <a target="_blank" @click="addDep(item.key, item.title)" rel="noopener noreferrer">新建下级部门</a>
              </a-menu-item>
              <a-menu-item key="1">
                <a
                  target="_blank"
                  :style="{ cursor: item.key.indexOf('tenant') > -1 ? 'not-allowed' : 'pointer' }"
                  @click="addDep(item.parentId, item.parentName, item.key)"
                  rel="noopener noreferrer"
                  >新建同级部门</a
                >
              </a-menu-item>
              <!--               :disabled=""-->
              <a-menu-item target="_blank" @click="editDep(item)" key="3">编辑</a-menu-item>
              <a-menu-item target="_blank" @click="changeStatus(item)" key="4">{{
                item.status == 1 ? '启用' : '停用'
              }}</a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
      </template>
    </a-tree>
  </div>
</template>

<script>
  import { mapActions, mapState } from 'vuex'
  var setSlot = (arr, parentId, parentName) => {
    for (let i = 0; i < arr.length; i++) {
      arr[i].scopedSlots = {
        title: 'custom',
      }
      if (parentId) {
        arr[i].parentId = parentId
        arr[i].parentName = parentName
      }
      if (arr[i].children.length > 0) {
        setSlot(arr[i].children, arr[i].key, arr[i].title)
      }
    }
    return arr
  }
  export default {
    name: 'depTree',
    props: {
      // 树结构数据
    },
    data() {
      return {
        expandedKeys: [],
        dataList: [],
        autoExpandParent: true,
        selectKey: [],
        confirmVisible: {},
        itemIndex: '',
        searchValue: '',
        depSearch: {
          searchName: '',
        },
      }
    },
    computed: {
      ...mapState({
        loading: state => state.SysDepartment.loading,
        treeData: state => {
          let treeData = state.SysDepartment.treeData
          let arr = JSON.parse(JSON.stringify(treeData))
          return setSlot(arr)
        },
      }),
    },
    created() {
      this.getDepTree().then(res => {
        this.selectKey = [res[0].key]
        this.expandedKeys = [res[0].key]
        this.generateList(res)
        this.$emit('selectDep', res[0].key)
      })
    },
    methods: {
      ...mapActions({
        getDepTree: 'SysDepartment/getTree',
      }),
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      generateList(data) {
        for (let i = 0; i < data.length; i++) {
          const node = data[i]
          if (node.scopedSlots === undefined) {
            node.scopedSlots = { title: 'title' }
          }
          this.dataList.push({ key: node.key, title: node.title })
          if (node.children) {
            this.generateList(node.children)
          }
        }
      },
      getParentKey(key, tree) {
        let parentKey
        for (let i = 0; i < tree.length; i++) {
          const node = tree[i]
          if (node.children) {
            if (node.children.some(item => item.title === key)) {
              parentKey = node.key
            } else if (this.getParentKey(key, node.children)) {
              parentKey = this.getParentKey(key, node.children)
            }
          }
        }
        this.treeData = tree
        return parentKey
      },
      onChange(e) {
        const value = e.target.value
        const expandedKeys =
          value === ''
            ? ['0']
            : this.dataList
                .map(item => {
                  if (item.title.indexOf(value) > -1) {
                    let data = JSON.parse(JSON.stringify(this.$store.state.SysDepartment.treeData))
                    return this.getParentKey(item.title, data)
                  }
                  return null
                })
                .filter((item, i, self) => item && self.indexOf(item) === i)
        if (expandedKeys.length === 0) {
          this.$message.info('无搜索对应的部门')
        }
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        })
      },
      selectNode(selectedKeys, e) {
        this.selectKey = selectedKeys
        if (selectedKeys && selectedKeys.length > 0) {
          this.$emit('selectDep', selectedKeys[0])
        }
      },
      addDep(parentId, parentName, key) {
        if (key && key.indexOf('tenant') > -1) {
          return
        }
        this.$emit('addDep', parentId, parentName)
      },
      editDep(item) {
        this.$emit('editDep', item)
      },
      changeStatus(item) {
        let id = item.key
        let status = item.status
        this.$emit('changeStatus', id, status)
      },
      getDepTreeData() {
        this.dataList = []
        this.getDepTree(this.depSearch).then(res => {
          this.generateList(res)
        })
      },
    },
  }
</script>

<style lang="less" scoped>
  .tree-todo {
    display: none;
    margin-left: 10px;
    float: right;
  }
  .ant-tree li .ant-tree-node-content-wrapper:hover {
    .tree-todo {
      display: inline-block;
    }
  }
  .depStop {
    color: red;
  }
  .tree-title {
    display: inline-block;
    width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
